package com.badibadi.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.amap.api.location.AMapLocation;
import com.badibadi.activity.ActivityOverViewActivity;
import com.badibadi.activity.PeopleNearByActivity;
import com.badibadi.adapter.AfterLandingMyHomePageAllAdapter_1;
import com.badibadi.adapter.Popwindows_Adapter;
import com.badibadi.fragment.ActivityMyActivityFragment0.getFragmentData;
import com.badibadi.infos.Activity_Overview_Model;
import com.badibadi.infos.ClueTypeModel;
import com.badibadi.infos.ListsModel;
import com.badibadi.infos.Results;
import com.badibadi.infos.clubs_main_Model;
import com.badibadi.mytools.AMapLocationUtils;
import com.badibadi.mytools.CalendarTools;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.Dialog;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MySharePreferences;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.TempTools;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.ViewHolder;
import com.badibadi.mytools.AMapLocationUtils.getAMapLocation;
import com.badibadi.uniclubber.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class ActivityOverViewFragment0 extends BaseFragment implements
		IXListViewListener {
	protected static final String TAG = "ActivityOverViewFragment0";
	private AfterLandingMyHomePageAllAdapter_1 x1Adapter;
	private XListView xListView1;
	private PopupWindow popup = null;
	private int Page;// 当前显示数据页数
	private int Type;// 显示类型
	private String type_id = null, content = null, uid;
	private double jingdu, weidu;
	private List<Activity_Overview_Model> activity_Overview_Models;
	private int languageType = 0;
	private MySharePreferences preferences;
	private List<ClueTypeModel> clueTypeModels;
	private ListsModel listsModel;
	private Popwindows_Adapter popwindows_Adapter;
	private ListView type_list;
	private Results results;
	private List<Activity_Overview_Model> list;
	private ClueTypeModel model;
	private Message message;
	private Bundle bundle;

	private TextView tv_search;
	private LinearLayout seach_ll;
	private boolean isReturnUp = true;// 按返回键是否回退关键字
	private boolean isSouSuo1 = true;
	private boolean isSouSuo2 = true;
	// 查询关键字相关
	private String searchName = null;
	private String tid = null;// 活动类型id
	private String yincang = null;// 判断搜索和类别栏是否隐藏的参数

	private AutoCompleteTextView index_autocomplete_txt_view;
	private String LanguageType;// 语言区分
	private ImageView fragment_calendar_clear;// 清空搜索内容
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_net_error));
					xListView1.stopRefresh();
					xListView1.stopLoadMore();
					xListView1.setRefreshTime(""+getResources().getString(R.string.ganggang));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 2:
				try {
					Utils.ExitPrgress(getActivity());

					activity_Overview_Models.addAll(list);
					x1Adapter.notifyDataSetChanged();
					xListView1.stopRefresh();
					xListView1.stopLoadMore();
					xListView1.setRefreshTime(""+getResources().getString(R.string.ganggang));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				try {
					Utils.ExitPrgress(getActivity());
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xa10));
					xListView1.stopRefresh();
					xListView1.stopLoadMore();
					xListView1.setRefreshTime(""+getResources().getString(R.string.ganggang));
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 4:
				try {
					Utils.ExitPrgress(getActivity());
					if (clueTypeModels != null) {
						clueTypeModels.clear();
					}
					if (listsModel.getLists() != null
							&& !listsModel.getLists().isEmpty()) {
						for (int i = 0; i < listsModel.getLists().size(); i++) {
							ClueTypeModel clueTypeModel = new ClueTypeModel();
							clueTypeModel.setId(listsModel.getLists().get(i)
									.getId());
							clueTypeModel.setName(listsModel.getLists().get(i)
									.getName());
							clueTypeModel.setNum(listsModel.getLists().get(i)
									.getNum());
							clueTypeModels.add(clueTypeModel);
						}
					}
					popwindows_Adapter = new Popwindows_Adapter(clueTypeModels,
							getActivity());
					type_list.setAdapter(popwindows_Adapter);
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;

			default:
				break;
			}
		}
	};
	private LinearLayout acticity_overview0_btn_type;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	@Override
	public void onDestroy() {
	
		super.onDestroy();
		ImageLoader.getInstance().clearDiscCache();
		ImageLoader.getInstance().clearMemoryCache();
	}

	@Override
	public View onCreateView(final LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.activity_overview_importylayout,
				null);
		Page = 1;
		Type = getArguments().getInt("type", 1);
		yincang = getArguments().getString("yincang");
		LanguageType = Dialog.getSystemLanguageTypegrzx(getActivity());
		try {
			tid = getArguments().getString("TYPE_id");
			uid = getArguments().getString("uid");
		} catch (Exception e) {
			// TODO: handle exception
		}
		clueTypeModels = new ArrayList<ClueTypeModel>();
		tv_search = (TextView) view.findViewById(R.id.TheKeyword);
		seach_ll = (LinearLayout) view.findViewById(R.id.seach_ll);
		fragment_calendar_clear = (ImageView) view
				.findViewById(R.id.fragment_calendar_clear);
		activity_Overview_Models = new ArrayList<Activity_Overview_Model>();
		x1Adapter = new AfterLandingMyHomePageAllAdapter_1(
				activity_Overview_Models, getActivity(), Type, weidu, jingdu,
				"1");
		preferences = new MySharePreferences(getActivity(), "language");
		languageType = preferences.get("language", 0);
//		   
		if (yincang != null && yincang.equals("yes")) {
//			   
			seach_ll.setVisibility(View.GONE);
		}
		InitMyXListView1(view);
		if (Type == 3) {
			if (tid != null) {
				isSouSuo1 = false;
				seach_ll.setVisibility(View.GONE);
			}
			location();
		} else {
			if (tid != null) {
				isSouSuo1 = false;
				seach_ll.setVisibility(View.GONE);
				// Page = 1;
				// activity_Overview_Models.clear();
				// x1Adapter.notifyDataSetChanged();
				Activity_show(Type, Page, tid, searchName);
			} else {
				Activity_show(Type, Page, null, content);
			}
		}
		acticity_overview0_btn_type = (LinearLayout) view
				.findViewById(R.id.fragment_club_overview0_btn_type);
		acticity_overview0_btn_type
				.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						OpenOrClosePopWindows(inflater, v);
					}
				});

		view.findViewById(R.id.search_button).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (isSouSuo1) {
							searchName = index_autocomplete_txt_view.getText()
									.toString().trim();
							message = new Message();
							bundle = new Bundle();
							message.what = 1;
							isSouSuo2 = false;
							bundle.putString("tital_name", "“" + searchName
									+ "”");
							message.setData(bundle);
							Constants.Activity_tital_handler
									.sendMessage(message);
							Page = 1;
							activity_Overview_Models.clear();
							x1Adapter.notifyDataSetChanged();
							Activity_show(Type, Page, tid, searchName);
						} else {

						}
					}
				});
		index_autocomplete_txt_view = (AutoCompleteTextView) view
				.findViewById(R.id.index_autocomplete_txt_view);
		index_autocomplete_txt_view.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable arg0) {
				content = arg0.toString();
				if (content.length() == 0) {
					Activity_show(Type, ++Page, null, null);
				}
			}
		});
		fragment_calendar_clear.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				index_autocomplete_txt_view.setText("");
			}
		});

		return view;
	}

	private void Activity_show(final int type, final int page,
			final String type_id, final String content) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				list = new ArrayList<Activity_Overview_Model>();
				Map<String, Object> map = new HashMap<String, Object>();
				//    
				// "Dialog="
				// + Dialog.getSystemLanguageTypegrzx(getActivity()));
				map.put("languageType", LanguageType);
				map.put("type", type);
				map.put("page", page);
				map.put("pageNum", 6);
//				map.put("uid", uid);
				if (type_id != null) {
					map.put("type_id", type_id);
				}
				if (content != null) {
					map.put("search_name", content);
				}
				if (Type == 3) {
					try {
						map.put("arr", fengzhuang_jingweidu());
						map.put("distance", "10");// 查询的距离（长度km）
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						   
					}
				}
//				   
				//    ("活动总览提交的数据是:" + map.toString());
				String actcontent = Utils.sendRequest(map, Constants.BadiUrl
						+ "activity_show");
				System.out.println("huodongzonglan"+actcontent);
				if (actcontent != null) {
					//    ("活动总览返回结果是:" + actcontent);
//					   
					results = Utils.checkResult_NNN(getActivity(), actcontent);
					if (results != null && !results.getRetmsg().equals("null")
							&& results.isRet()) {
						try {
							list = JSONUtils.getListByJsonString(
									results.getRetmsg(),
									Activity_Overview_Model.class);
							System.out.println("aa"+results.getRetmsg());
							mHandler.sendEmptyMessage(2);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						if (page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						mHandler.sendEmptyMessage(3);
					}
				} else {
					if (page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					mHandler.sendEmptyMessage(1);
				}
			}
		});
	}

	private JSONObject fengzhuang_jingweidu() throws JSONException {
		JSONObject object = new JSONObject();
		object.put("map_y", jingdu);// jingdu
		object.put("map_x", weidu);// weidu
		return object;
	}

	private void Show_type_activity() {
		Utils.showPrgress(getActivity());
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				listsModel = new ListsModel();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", "huodong");
				map.put("languageType", TempTools.BackLanguage(languageType));
				String acticontent = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "type/listType");
//				   
				if (acticontent != null) {
					Results results = Utils.checkResult_NNN(getActivity(),
							acticontent);
//					   
					if (results != null && results.getRetmsg() != null) {
						//    ("结果是:" + results.getRetmsg());
						try {
							listsModel = JSONUtils.getEntityByJsonString(
									results.getRetmsg(), ListsModel.class);
							System.out.println("type"+results.getRetmsg());
							mHandler.sendEmptyMessage(4);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						mHandler.sendEmptyMessage(3);
					}
				} else {
					mHandler.sendEmptyMessage(1);
				}
			}
		});
	}

	/**
	 * 打开或管理悬浮对话框
	 * 
	 * @param inflater
	 * @param v
	 */
	public void OpenOrClosePopWindows(LayoutInflater inflater, View v) {

		View root = inflater.inflate(
				R.layout.fragment_club_overview_popwindows, null);
		popup = new PopupWindow(root, LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
				
		type_list = (ListView) root.findViewById(R.id.type_list);		
		type_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Utils.showPrgress(getActivity());
				tid = clueTypeModels.get(position).getId();
				if (isSouSuo2) {
					message = new Message();
					bundle = new Bundle();
					message.what = 1;
					bundle.putString("tital_name", clueTypeModels.get(position)
							.getName());
					message.setData(bundle);
					Constants.Activity_tital_handler.sendMessage(message);
					isSouSuo1 = false;
					seach_ll.setVisibility(View.GONE);
					Page = 1;
					activity_Overview_Models.clear();
					x1Adapter.notifyDataSetChanged();
					Activity_show(Type, Page, tid, searchName);
				} else {
					Page = 1;
					isSouSuo1 = false;
					tv_search.setVisibility(View.VISIBLE);
					seach_ll.setVisibility(View.GONE);
					tv_search.setText(clueTypeModels.get(position).getName());
					seach_ll.setVisibility(View.GONE);
					activity_Overview_Models.clear();
					x1Adapter.notifyDataSetChanged();
					Activity_show(Type, Page, tid, searchName);
				}
				if (popup != null) {
					popup.dismiss();
				}
			}
		});
		popup.setBackgroundDrawable(new BitmapDrawable());
		popup.setFocusable(true);
		popup.setTouchable(true);
		Show_type_activity();
		popup.showAsDropDown(v);

	}

	public void InitMyXListView1(View view) {
		xListView1 = (XListView) view
				.findViewById(R.id.after_landing_friends00_xlistView2);
		// xListView1.setDividerHeight(10);
		xListView1.setPadding(10, 10, 10, 10);
		xListView1.setXListViewListener(this);
		xListView1.setPullLoadEnable(true);
		xListView1.setPullRefreshEnable(true);
		xListView1.setAdapter(x1Adapter);
		// xListView1.startRefresh();
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		Page = 1;
		if (activity_Overview_Models != null) {
			activity_Overview_Models.clear();
		}
		Activity_show(Type, Page, tid, content);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		Activity_show(Type, ++Page, tid, content);
	}

	/**
	 * 点击回退键之后的操作回退到上一级
	 * 
	 * @param get
	 */
	public void getSearchIsReturnUp_1(getFragmentData_1 get) {
		get.getIsReturnUp_1(isReturnUp);
		if (seach_ll.getVisibility() == 8) {
			isSouSuo1 = true;
			tid = null;
			seach_ll.setVisibility(View.VISIBLE);
			tv_search.setVisibility(View.GONE);
			if (isSouSuo2) {
				message = new Message();
				bundle = new Bundle();
				message.what = 1;
				bundle.putString("tital_name",
						getResources().getString(R.string.l_xb9));
				message.setData(bundle);
				Constants.Activity_tital_handler.sendMessage(message);
				Page = 1;
				activity_Overview_Models.clear();
				x1Adapter.notifyDataSetChanged();
				Activity_show(Type, Page, tid, searchName);
			}
		} else if (seach_ll.getVisibility() == 0 && searchName != null) {
			isSouSuo2 = true;
			searchName = null;
			message = new Message();
			bundle = new Bundle();
			message.what = 1;
			bundle.putString("tital_name",
					getResources().getString(R.string.l_xb9));
			message.setData(bundle);
			Constants.Activity_tital_handler.sendMessage(message);
			Page = 1;
			activity_Overview_Models.clear();
			x1Adapter.notifyDataSetChanged();
			Activity_show(Type, Page, tid, searchName);
		} else {
			((getActivity())).finish();
			getActivity().overridePendingTransition(R.anim.slide_left2,
					R.anim.slide_right2);
		}
	}

	public interface getFragmentData_1 {
		// 是否返回到上一级returnSearch
		void getIsReturnUp_1(boolean isReturn);
	}

	private void location() {
		// 这只是一个使用接口的模板
		final AMapLocationUtils aMapLocationUtils = new AMapLocationUtils(
				getActivity());
		new Thread(new Runnable() {
			boolean isRun = true;

			@Override
			public void run() {
				// TODO Auto-generated method stub

				while (isRun) {
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						   
					}
					aMapLocationUtils
							.setOnAMapLocationClistener(new getAMapLocation() {

								@Override
								public void getAMapLocation(
										AMapLocation aMapLocation) {
									// TODO Auto-generated method stub
									if (aMapLocation != null) {
										//    
										// "经度-》"
										// + aMapLocation
										// .getLongitude()
										// + "纬度=》"
										// + aMapLocation
										// .getLatitude());
										jingdu = aMapLocation.getLongitude();
										weidu = aMapLocation.getLatitude();
										x1Adapter.setMap_x(weidu);
										x1Adapter.setMap_y(jingdu);
										isRun = false;
										if (tid != null) {
											// Page = 1;
											// activity_Overview_Models.clear();
											// x1Adapter.notifyDataSetChanged();
											Activity_show(Type, Page, tid,
													searchName);
										} else {
											Activity_show(Type, Page, null,
													content);
										}
									}

								}
							});
				}

			}
		}).start();
	}
}
